package at.fhj.pse.datasource.impl;

import java.io.Serializable;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import at.fhj.pse.datasource.EmployeeDAO;
import at.fhj.pse.datasource.exception.DatasourceLayerException;
import at.fhj.pse.datasource.model.Employee;

public class EmployeeDAOImpl implements EmployeeDAO, Serializable {

	private static final long serialVersionUID = 6465738835662128547L;

	private final Logger LOG = Logger
			.getLogger(EmployeeDAOImpl.class.getName());

	// see META-INF/persistence.xml for persistence unit configuration
	@Inject
	private EntityManager em;

	@Override
	public Employee getEmployeeByUsername(String username) {
		if (username == null) {
			throw new DatasourceLayerException("username is null", new IllegalArgumentException());
		}
		LOG.info("getEmployee(" + username + ")");
		Employee emp = (Employee) em
				.createQuery(
						"select emp from Employee emp where username = '"
								+ username + "'").getResultList().get(0);
		return emp;
	}

	@Override
	public Employee getEmployeeById(Long id) {
		LOG.info("getEmployeeById(" + id + ")");
		Employee emp = (Employee) em.find(Employee.class, id);
		return emp;
	}

	@Override
	public Employee checkLogin(String username, String password) {
		if (username == null) {
			throw new DatasourceLayerException("username is null", new IllegalArgumentException());
		}
		if (password == null) {
			throw new DatasourceLayerException("password is null", new IllegalArgumentException());
		}
		Employee employee;
		try {
			Object obj = this.em
					.createQuery(
							"SELECT e FROM Employee e WHERE e.username LIKE :username AND e.password LIKE :password")
					.setParameter("username", username)
					.setParameter("password", password).getSingleResult();
			employee = (Employee) obj;
			return employee;
		} catch (javax.persistence.NoResultException  | NullPointerException ex) {
			employee = null;
			throw new DatasourceLayerException("Falsche Benutzernamen/Passwort Kombination.", ex);
		}
	}

}